package com.show.filter;


import com.show.HelpClazz;
import com.show.dto.sys_emp.SysEmp;
import com.show.dto.sys_menu.SysMenu;
import com.show.filter.dto.AccessToken;
import com.show.filter.dto.LoginPara;
import com.show.filter.jwtUtil.JwtHelper;
import com.show.service.emp.EmpService;
import com.show.service.sys_menu.MenuService;
import com.show.util.Md5Salt;
import com.show.util.HelperClazz;
import com.show.util.ResultMsg;
import com.show.util.ResultStatusCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.bind.DatatypeConverter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 王玉涛
 * @Param
 * @date 2017/7/29 8:35
 */
@Controller
public class LoginController {

    @Autowired
    private EmpService empService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private Md5Salt md5Salt;

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String tologin() {
        return "login";
    }

    @RequestMapping(value = "error", method = RequestMethod.GET)
    public String error() {
        return "error";
    }

    @PostMapping("index")
    @ApiOperation(value = "返回首页", notes = "")
    public String login(LoginPara loginPara, Map<String, Object> map, HttpServletRequest request) {
        try {
            //验证码验证
            String code = request.getParameter("code");
            HttpSession session = request.getSession();
            String sessionCode = (String) session.getAttribute("code");
            //忽略验证码大小写
//            if (!StringUtils.equalsIgnoreCase(code, sessionCode)) {
//                map.put("codeError","验证码错误");
//                throw new RuntimeException("验证码对应不上code=" + code + "  sessionCode=" + sessionCode);
//            }
            //登陆验证
            //指向token服务用的key
            loginPara.setClientId(HelpClazz.CLIENTID);
            //校验用户是否存在
            //盐值加密
            String pwd = md5Salt.getMD5(loginPara.getLoginPwd());
            SysEmp newemp = empService.getEmp(loginPara.getLoginName(), pwd);
            if (null == newemp) {
                map.put("error","用户名密码错误，请重新填写");
                return "login";
            }
            String roleName = empService.getRoleName(newemp.getEmpId());
            //去掉密码传递
            loginPara.setLoginPwd(null);
            loginPara.setEmpName(newemp.getEmpName());
            ResultMsg resultMsg;
            String accessToken = JwtHelper.createJWT(loginPara.getLoginName(), loginPara.getEmpName(),
                    "", HelpClazz.CLIENTID, HelpClazz.NAME,
                    //超时和密钥
                    HelpClazz.EXPIRESSECOND * 1000, HelpClazz.SECRET);

            // 返回accessToken
            AccessToken accessTokenEntity = new AccessToken();
            accessTokenEntity.setAccess_token(accessToken);
            accessTokenEntity.setEmpName(newemp.getEmpName());
            accessTokenEntity.setCdate(newemp.getCdate());
            accessTokenEntity.setEmail(newemp.getEmail());
            accessTokenEntity.setEmpCode(newemp.getEmpCode());
            accessTokenEntity.setEmpMode(newemp.getEmpMode());
            accessTokenEntity.setSts(newemp.getSts());
            accessTokenEntity.setRoleName(roleName);
            accessTokenEntity.setLoginName(newemp.getLoginName());
            accessTokenEntity.setEmpTel(newemp.getContactNumber());
            accessTokenEntity.setEmpSex(newemp.getGender());
            accessTokenEntity.setExpires_in(HelpClazz.EXPIRESSECOND);
            accessTokenEntity.setToken_type("bearer");
            resultMsg = new ResultMsg(ResultStatusCode.OK.getErrcode(), ResultStatusCode.OK.getErrmsg(),
                    accessTokenEntity);
            //查询当前登陆人角色ID
            String role_id = menuService.getRoleId(loginPara.getLoginName());
            //查询当前登陆人全部菜单
            List<SysMenu> menuList = menuService.getMenus(loginPara.getLoginName(),role_id);


            map.put("token", accessToken);
            map.put("userName", newemp.getLoginName());
            map.put("list",menuList);
            request.getSession().setAttribute("token", accessToken);
            return "index";

        } catch (Exception ex) {
            ex.printStackTrace();
            return "login";
        }
    }

    public static Claims parseJWT(String jsonWebToken, String base64Security) {
        try {
            Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
                    .parseClaimsJws(jsonWebToken).getBody();
            return claims;
        } catch (Exception ex) {
            return null;
        }
    }

    @RequestMapping(value = "/analyseToken", method = RequestMethod.POST)
    public Map analyseToken(@RequestBody String token) {
        Claims mm = parseJWT(token, "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=");
        String s = (String) mm.get("userid");
        Map result = new HashMap();
        result.put("cusername", s);
        return result;

    }

    /**
     * 获取当前登陆人配置菜单和获取登陆人姓名
     * @param userName
     * @return
     */
    public List<SysMenu> getMenus(String userName) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //查询当前登陆人角色ID
        String role_id = menuService.getRoleId(userName);
        //查询当前登陆人全部菜单
        List<SysMenu> menuList = menuService.getMenus(userName,role_id);
        for (int i = 0; i < menuList.size(); i++) {
            map.put("menu" + i, menuList.get(i).getMenuName());
            map.put("menu0" + i, menuList.get(i).getSysMenuList());
        }
        return menuList;
    }

    /**
     * 获取登陆人姓名
     * @param userName
     * @return
     */
    public String getEmp(String userName) {
        SysEmp empName = empService.getEmpByLogin(userName);
        return empName.getEmpName();
    }

    /**
     * 获取登陆人id
     * @param userName
     * @return
     */
    public Integer getEmpId(String userName) {
        SysEmp empName = empService.getEmpByLogin(userName);
        return empName.getEmpId();
    }


}
